<template>
  <!-- 订单列表 -->
  <div>
    <van-nav-bar fixed :title="title" left-arrow @click-left="$utils.back($route.path);">
      <template #right>
        <svg-icon icon-class="filter" class="fs-44 color-dark" @goPage="openDatePicker" />
      </template>
    </van-nav-bar>
    <div class="has-top">
      <!-- 搜索栏 -->
      <top-search
        type="primary"
        :val="val"
        :area-show="areaShow"
        input-style="inputStyle-1"
        placeholder="快速查找订单"
        @search="search"
      />
      <div class="page-content-box mlr-25">
        <div class="flex-s-c tabber-box-1">
          <van-tabbar v-model="active" :fixed="fixed" :border="border" @change="onChange">
            <van-tabbar-item v-for="(item,index) in filterList" :key="index">{{ item }}</van-tabbar-item>
          </van-tabbar>
        </div>
        <!-- 列表 -->
        <div v-for="(item,index) in orderList" :key="index" class="bg-white br-12 pb-50 mb-25 item" @click="gotoDetail(item.ID)">
          <div :class="item.show?'item-toggle-up':'item-toggle-down'" class="item-toggle " @click.stop="item.show = !item.show" />
          <div class="color-gray hb flex-s-c pd-20">
            <div class="flex-1">
              <p>订单编号：</p>
              <p>{{ item.OrderNo }}</p>
            </div>
            <div class="flex-1">
              <p>下单时间：</p>
              <p>{{ item.AddTime }}</p>
            </div>
          </div>
          <div class="pt-18" :class="item.show?'show-circle pb-20 ':''">
            <div class="flex-s-c info-item">
              <p v-show="requestData.type===1" class="fs-26">采购商：</p>
              <p v-show="requestData.type===0" class="fs-26">供应商：</p>
              <p class="fs-26">订单实收款：</p>
            </div>
            <div class="flex-s-c info-item">
              <p v-show="requestData.type===1" class="fs-26">{{ item.OrdNickName }}</p>
              <p v-show="requestData.type===0" class="fs-26">{{ item.PurchaseMemberName }}</p>
              <p class="color-primary fs-36">¥{{ item.PriceSum }}</p>
            </div>
            <div class="flex-s-c info-item">
              <p class="color-primary">共{{ item.DetailList.length }}款产品，{{ item.ProductCount }}件 </p>
              <p>
                <span v-show="item.State===0&&(type==='0'||type==='1')" class="btn-small bg-primary" @click.stop="check(item,index)">审核</span>
                <span v-show="item.State===0&&type==='2'" class="btn-small  bg-c">待审核</span>
                <span v-show="item.State===0&&type==='-1'" class="btn-small hollow-btn-current" style="color:#333;" @click.stop="check(item,index)">取消订单</span>
                <span v-show="item.State===1&&(type==='0'||type==='2')" class="btn-small bg-primary" @click.stop="check(item,index)">发货</span>
                <span v-show="item.State===1&&(type==='-1'||type==='1')" class="btn-small  bg-c">待发货</span>
                <span v-show="item.State===2" class="btn-small bg-c">已取消</span>
                <span v-show="item.State===3&&type!=='-1'" class="btn-small bg-c">已发货</span>
                <span v-show="item.State===3&&type==='-1'" class="btn-small bg-primary" @click.stop="check(item,index)">确认收货</span>
                <span v-show="item.State===4" class="btn-small bg-danger" @click.stop="check(item,index)">已驳回</span>
                <span v-show="item.State===5" class="btn-small bg-success">已完成</span>
              </p>
            </div>
          </div>
          <ProductList v-show="item.show" :product-list="item.DetailList" list-type="orderDetail" class="pos-r" style="z-index:0;" />
        </div>
        <no-data v-if="orderList.length === 0" />
        <p v-if="end===true&&orderList.length!==0" class="tac fs-24 ptb-40 color-gray-light">无更多数据</p>
      </div>
    </div>
    <!-- 弹出框 -->
    <van-dialog v-model="dialogData.show" close-on-click-overlay :show-confirm-button="dialogData.confirmButton">
      <div class="plr-60 pt-20 pb-40 dialog-content">
        <!-- 审核订单 -->
        <div v-show="dialogData.State===0&&(type==='0'||type==='1')">
          <h1 class="dialog-tle">审核订单</h1>
          <p class="flex-s-c dialog-input " :class="checkData.checkResult===2?'dialog-input-active':''" @click="checkData.checkResult=2">
            <span class="color-gray" :class="checkData.checkResult===2?'fw-b':''">驳回</span>
            <span class="radio" />
          </p>
          <p class="flex-s-c dialog-input" :class="checkData.checkResult===1?'dialog-input-active':''" @click="checkData.checkResult=1">
            <span class="color-gray" :class="checkData.checkResult===1?'fw-b':''">通过</span>
            <span class="radio" />
          </p>
          <van-field v-model="checkData.checkMsg" type="textarea" class="textarea" placeholder="审核备注" />
        </div>

        <!-- 取消订单 -->
        <div v-show="dialogData.State===0&&type==='-1'">
          <h1 class="dialog-tle">提示</h1>
          <p class="fs-36 color-black mt-30 tac">您确定要取消该订单吗？</p>
          <van-field v-model="cancleData.checkMsg" type="textarea" class="textarea" placeholder="取消备注" />
        </div>
        <!-- 发货 -->
        <div v-show="dialogData.State===1">
          <h1 class="dialog-tle">发货</h1>
          <p class="flex-s-c dialog-input " :class="activeInput===0?'dialog-input-active':''" @click="choseT">
            <span class="color-gray  flex-s-0">快递公司</span>
            <span v-if="!expressName" class="color-gray-light pl-50 flex-1">快递公司名称</span>
            <span v-else class="color-gray pl-50 flex-1">{{ expressName }}</span>
          </p>
          <p class="flex-s-c dialog-input" :class="activeInput===1?'dialog-input-active':''" @click="activeInput=1">
            <span class="color-gray flex-s-0">快递单号</span>
            <input v-model="sendData.expressCode" class="flex-1 color-gray pl-50" style="line-height:1;" type="text" placeholder="请输入单号（必填）">
          </p>
        </div>
        <!-- 确认收获 -->
        <div v-show="dialogData.State===3">
          <h1 class="dialog-tle">提示</h1>
          <p class="fs-36 color-black mt-30 tac">您要确认收货吗？</p>
        </div>

        <!-- 驳回理由 -->
        <div v-show="dialogData.State===4">
          <h1 class="dialog-tle">驳回理由</h1>
          <div class="textarea fs-28">{{ dialogData.checkMsg }}</div>
        </div>

        <div v-show="dialogData.State===0||dialogData.State===1||dialogData.State===3" class="flex-s-c dialog-btn-box">
          <span class="hollow-btn btn-middle" @click="cancle">取消</span>
          <span class="solid-btn btn-middle" @click="confirm">确定</span>
        </div>
        <div v-show="dialogData.State===4" class="flex-center dialog-btn-box">
          <span class="solid-btn btn-middle" @click="cancle">确定</span>
        </div>
      </div>
    </van-dialog>

    <!-- 物流公司选择 -->
    <van-popup v-model="showPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        class="color-primary"
        @cancel="showPicker = false"
        @confirm="choseExpress"
      />
    </van-popup>

    <!-- 时间选择弹窗 -->
    <div v-show="datePickerShow" class="filter-popup">
      <div class="filter-bg" @click="closeDatePicker" />
      <div class="filter-content plr-25 pb-25">
        <h2 class="fs-32 lh-lg fw-b">订单时间</h2>
        <div class="flex-s-c mt-10">
          <span v-for="(item,index) in dataList" :key="index" class="filter-item" :class="activeDateInd===index?'activeDate':''" @click="changeDate(index)">{{ item }}</span>
        </div>
        <div class="flex-s-c mt-30">
          <input v-model="StartTime" type="text" class="filter-input" placeholder="请选择开始时间" @change="activeDateInd=-1">
          <span>——</span>
          <input v-model="EndTime" type="text" class="filter-input" placeholder="请选择结束时间" @change="activeDateInd=-1">
        </div>
        <div class="flex-center mt-30">
          <div class="btn-small bg-primary tac " @click="onConfirm">确定</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TopSearch from 'components/Search'
import noData from 'components/noData'
import stateFilter from 'components/stateFilter'
import ProductList from 'components/productList'
import { GetPurchaseOrderListPage, CheckPurchaseOrder, GetExpressList, SendPurchaseOrder, CanclePurchaseOrder, ReceivePurchaseOrder } from 'api/purchase'
export default {
  components: {
    TopSearch,
    noData,
    stateFilter,
    ProductList
  },
  data() {
    return {
      // 标题
      title: '全部订单',

      // 搜索栏配置及数据
      areaShow: false,
      val: '',

      // 标签栏
      filterList: [],
      fixed: false,
      border: false,
      active: 0,

      // 时间选择栏
      datePickerShow: false,
      dataList: ['今日', '本周', '本月', '本年'],
      activeDateInd: -1,
      StartTime: '',
      EndTime: '',

      // 订单列表
      orderList: [],
      columns: [],
      expressList: [],
      hasExpressList: false,
      localIndex: -1,

      // 列表类型
      type: '0',

      // 请求参数
      requestData: {
        PageIndex: 1,
        PageSize: 4,
        type: 1
      },

      // 审核参数
      checkData: {
        ordId: 0,
        checkResult: 1,
        checkMsg: ''
      },

      // 发货
      sendData: {
        purchaseOrderId: 0,
        expressCode: '',
        expressId: 0
      },
      activeInput: -1,

      // 取消订单
      cancleData: {
        ordId: 0,
        checkMsg: ''
      },

      // 确认收货
      submitData: {
        ordId: 0
      },

      expressName: '',
      // 弹窗参数
      dialogData: {
        State: -2,
        checkMsg: '',
        show: false,
        confirmButton: false
      },

      // 选择器参数
      showPicker: false,

      // 滚动状态
      totalAmout: 0,
      scollRequest: true,
      scollTop: 0,
      end: false

    }
  },
  created() {
    this.initData()
  },
  mounted() {
    this.$nextTick(function() {
      window.addEventListener('scroll', this.onScroll)
    })
  },
  methods: {
    // 关键字搜索商品
    search(key) {
      console.log(key)
      this.resetParams()
      this.requestData.searchKey = key
      this.GetPurchaseOrderListPage()
    },
    changeDate(index) {
      this.activeDateInd = index
      switch (index) {
        case 0:
          this.StartTime = this.$utils.today().startDate
          this.EndTime = this.$utils.today().endDate
          break
        case 1:
          this.StartTime = this.$utils.thisWeek().startDate
          this.EndTime = this.$utils.thisWeek().endDate
          break
        case 2:
          this.StartTime = this.$utils.thisMonth().startDate
          this.EndTime = this.$utils.thisMonth().endDate
          break
        case 3:
          this.StartTime = this.$utils.thisYear().startDate
          this.EndTime = this.$utils.thisYear().endDate
          break
      }
    },

    initData() {
      this.resetParams()
      console.log(this.$route.params)
      this.type = this.$route.params.type
      if (this.type === '-1') {
        this.requestData.State = -1
        this.requestData.type = 0
        this.title = '采购订单'
        this.filterList = ['全部', '待审核', '待发货', '已取消', '已发货', '已驳回', '已完成']
      }
      if (this.type === '0') {
        this.requestData.State = -1
        this.requestData.type = 1
        this.title = '供货订单'
        this.filterList = ['全部', '待审核', '待发货', '已取消', '已发货', '已驳回', '已完成']
      }
      if (this.type === '1') {
        this.requestData.State = 0
        this.requestData.type = 1
        this.title = '审核订单'
        this.filterList = ['待审核', '已通过', '已驳回']
      }
      if (this.type === '2') {
        this.requestData.State = 1
        this.requestData.type = 1
        this.title = '发货订单'
        this.filterList = ['待发货', '已发货']
      }
      this.GetPurchaseOrderListPage()
    },
    resetParams() {
      this.requestData.PageIndex = 1
      this.requestData.PageSize = 4
      this.orderList = []
      this.totalAmout = 0
      this.scollRequest = true
      this.scollTop = 0
      this.end = false
    },
    resetOptParams() {
      this.checkData.ordId = 0
      this.checkData.checkResult = 1
      this.activeInput = -1
      this.checkData.checkMsg = ''
      this.sendData.purchaseOrderId = 0
      this.sendData.expressCode = ''
      this.sendData.expressId = 0
      this.cancleData.ordId = 0
      this.cancleData.checkMsg = 0
      this.submitData.ordId = 0
      this.expressName = ''
    },
    choseT() {
      this.activeInput = 0
      if (this.hasExpressList) {
        this.showPicker = true
        return
      }
      this.GetExpressList()
    },
    // 审核/发货/查看驳回信息/确认收货/取消订单
    check(item, index) {
      this.localIndex = index
      this.checkData.ordId = item.ID
      this.sendData.purchaseOrderId = item.ID
      this.cancleData.ordId = item.ID
      this.submitData.ordId = item.ID
      this.dialogData.State = item.State
      this.dialogData.checkMsg = item.CheckMsg
      this.dialogData.show = true
    },
    confirm() {
      switch (this.dialogData.State) {
        // 确认审核
        case 0:
          if (this.type === '0' || this.type === '1') {
            if (this.checkData.checkResult !== 2 && this.checkData.checkResult !== 1) {
              this.$toast('请选择驳回或通过')
              return
            }
            if (this.checkData.checkResult === 2 && this.checkData.checkMsg === '') {
              this.$toast('请填写驳回原因')
              return
            }
            this.CheckPurchaseOrder()
          } else if (this.type === '-1') {
            this.CanclePurchaseOrder()
          }
          break
          // 确认发货
        case 1:
          if (this.sendData.expressId === 0) {
            this.$toast('请选择快递公司')
            return
          }
          if (!this.sendData.expressCode) {
            this.$toast('请输入快递单号')
            return
          }
          this.SendPurchaseOrder()
          break
          // 确认收货
        case 3:
          this.ReceivePurchaseOrder()
          break
          // 显示驳回理由
        case 4:
          this.dialogData.show = false
          break
      }
    },
    cancle() {
      this.checkData.checkResult = 1
      this.checkData.checkMsg = ''
      this.dialogData.show = false
    },
    choseExpress(val, index) {
      console.log(val, index)
      this.expressName = val
      this.sendData.expressId = this.expressList[index].ID
      this.showPicker = false
    },
    gotoDetail(id) {
      this.$router.push('/purchase/productOrderDetail/' + id)
    },
    onConfirm() {
      this.requestData.StartTime = this.StartTime
      this.requestData.EndTime = this.EndTime
      this.resetParams()
      this.GetPurchaseOrderListPage()
      this.datePickerShow = false
    },
    closeDatePicker() {
      this.StartTime = ''
      this.EndTime = ''
      this.activeDateInd = -1
      this.datePickerShow = false
    },
    openDatePicker() {
      this.StartTime = this.requestData.StartTime
      this.EndTime = this.requestData.EndTime
      if (
        this.StartTime === this.$utils.today().startDate &&
          this.EndTime === this.$utils.today().endDate) {
        this.activeDateInd = 0
      } else if (this.StartTime === this.$utils.thisWeek().startDate &&
          this.EndTime === this.$utils.thisWeek().endDate) {
        this.activeDateInd = 1
      } else if (this.StartTime === this.$utils.thisMonth().startDate &&
          this.EndTime === this.$utils.thisMonth().endDate) {
        this.activeDateInd = 2
      } else if (this.StartTime === this.$utils.thisYear().startDate &&
          this.EndTime === this.$utils.thisYear().endDate) {
        this.activeDateInd = 3
      }

      this.datePickerShow = true
    },
    onChange(index) {
      const _ind = index
      if (this.type === '0' || this.type === '-1') {
        this.requestData.State = _ind - 1
      }
      if (this.type === '1') {
        switch (_ind) {
          case 0:
            this.requestData.State = 0
            break
          case 1:
            this.requestData.State = 1
            break
          case 2:
            this.requestData.State = 4
            break
        }
      }
      if (this.type === '2') {
        switch (_ind) {
          case 0:
            this.requestData.State = 1
            break
          case 1:
            this.requestData.State = 3
            break
        }
      }
      this.resetParams()
      this.GetPurchaseOrderListPage()
    },
    GetPurchaseOrderListPage() {
      const _this = this
      GetPurchaseOrderListPage(this.requestData).then(res => {
        if (res && res.Data && res.Data.length > 0) {
          res.Data.forEach(item => {
            item.show = false
            _this.orderList.push(item)
          })
        }
        _this.totalAmout = res.TotalAmout
        _this.scollRequest = true
        if (_this.scollTop > 0) {
          document.body.scrollTo(0, _this.scollTop)
        }
      })
    },
    // 审核订单
    CheckPurchaseOrder() {
      CheckPurchaseOrder(this.checkData).then(res => {
        if (res) {
          console.log(res)
          this.resetOptParams()
          this.orderList.splice(this.localIndex, 1)
          this.dialogData.show = false
        }
      })
    },
    // 发货
    SendPurchaseOrder() {
      SendPurchaseOrder(this.sendData).then(res => {
        if (res) {
          console.log(res)
          this.resetOptParams()
          this.orderList.splice(this.localIndex, 1)
          this.dialogData.show = false
        }
      })
    },
    // 取消订单
    CanclePurchaseOrder() {
      CanclePurchaseOrder(this.cancleData).then(res => {
        if (res) {
          console.log(res)
          this.resetOptParams()
          this.orderList.splice(this.localIndex, 1)
          this.dialogData.show = false
        }
      })
    },
    // 确认收货
    ReceivePurchaseOrder() {
      ReceivePurchaseOrder(this.submitData).then(res => {
        if (res) {
          console.log(res)
          this.resetOptParams()
          this.orderList.splice(this.localIndex, 1)
          this.dialogData.show = false
        }
      })
    },
    GetExpressList() {
      const _this = this
      GetExpressList().then(res => {
        if (res) {
          _this.expressList = res.Data
          if (res.Data.length > 0) {
            res.Data.forEach(item => {
              _this.columns.push(item.Name)
            })
          }
          _this.hasExpressList = true
          _this.showPicker = true
        }
      })
    },

    // 滚动事件触发下拉加载
    onScroll() {
      const _this = this
      if (_this.scollRequest === true) {
        if (this.$utils.getScrollHeight() - this.$utils.getClientHeight() - this.$utils.getScrollTop() <= 5) {
          _this.scollRequest = false
          // alert('触发！！！')
          console.log('加载')
          _this.scollTop = this.$utils.getScrollTop()
          if (_this.requestData.PageIndex < _this.totalAmout) {
            _this.requestData.PageIndex++
            _this.GetPurchaseOrderListPage()
          } else {
            console.log('end')
            _this.end = true
          }
          // }
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.van-hairline--bottom::after{
  border-bottom: none;
}
.head-bg-box {
  height: 214px;
}
.total-box {
  min-height: 200px;
}
.item{
  position: relative;
  .item-toggle{
    position: absolute;
    left: calc(50% - 80px);
    bottom: -30px;
    width: 160px;
    height: 60px;
    border-radius: 50%;
    background: $colorF5;
  }
  .item-toggle-down{
    &:before,&:after{
      position: absolute;
      content: '';
      width: 20px;
      height: 4px;
      background: $black;
      right: 49%;
      bottom: 52%;
      -webkit-transform: rotate(25deg);
      transform: rotate(25deg);
    }
    &:after{
      left: 49%;
       -webkit-transform: rotate(-25deg);
      transform: rotate(-25deg);
    }
  }
  .item-toggle-up{
    &:before,&:after{
      position: absolute;
      content: '';
      width: 20px;
      height: 4px;
      background: $black;
      right: 49%;
      bottom: 52%;
      -webkit-transform: rotate(-25deg);
      transform: rotate(-25deg);
    }
    &:after{
      left: 49%;
       -webkit-transform: rotate(25deg);
      transform: rotate(25deg);
    }
  }
  .show-circle{
    position: relative;
    border-bottom: 1px solid $colorBorder;
    z-index: 1;
    &:before,&:after{
      content: '';
      position: absolute;
      width: 32px;
      height: 32px;
      border-radius: 100%;
      background: $colorF5;
      bottom: -16px;
      right: -16px;
      z-index: 1;
    }
    &:before{
      left: -16px;
    }
  }
  .info-item{
    p{
      text-align: center;
      width: 50%;
      flex-grow: 0;
      flex-shrink: 0;
      &.btn-small{
        width: auto;
      }
    }
  }
}
.dialog-content{
  .dialog-tle{
    text-align: center;
    font-size: 36px;
    position: relative;
    &:after{
      content: '';
      position: absolute;
      bottom: 10px;
      left: calc(50% - 80px);
      width: 160px;
      height: 16px;
      @include color-primary;
      background: linear-gradient(0deg, currentColor 0%, rgba(44, 211, 52, 0) 100%);
    }
  }
  .dialog-input{
    font-size: 28px;
    height: 76px;
    padding: 0 22px;
    color:$colorC;
    border: 1px solid currentColor;
    border-radius: 12px;
    margin-top: 30px;
    overflow: hidden;
    span{
      line-height: 1;
    }
    .radio{
      width: 40px;
      height: 40px;
      border-radius: 100%;
      color: $colorC;
      border: 1px solid currentColor;
    }
  }
  .dialog-input-active{
    @include color-primary;
    .radio{
      position: relative;
      @include color-primary;
      &:after{
        content:'';
        width: 20px;
        height: 20px;
        border-radius: 100%;
        @include bg-primary;
        position: absolute;
        top: calc(50% - 10px);
        left: calc(50% - 10px);
      }
    }
  }
  .textarea{
    background: #f4f4f4;
    margin-top: 30px;
    padding: 19px 22px;
    border-radius: 12px;
  }
  .dialog-btn-box{
    margin-top: 40px;
    .btn-middle{
      width: 220px;
    }
  }
}
.color-primary{
  /deep/.van-picker__cancel, /deep/.van-picker__confirm{
    color:currentColor;
  }
}
.tabber-box-1 {
  /deep/.van-tabbar {
    background: transparent;
    height: auto;
    justify-content: space-between;
    margin: 12px 0;
    overflow-y: hidden;
    overflow-x: scroll;
    .van-tabbar-item {
      font-size: 12px;
      line-height: 2;
      flex: auto;
      flex-shrink: 0;
      .van-tabbar-item__icon {
        margin: 0;
      }
      .van-tabbar-item__text {
        padding: 0 10px;
      }
    }
    .van-tabbar-item--active {
      color: $colorF;
      border-radius: 12px;
      @include bg-second;
    }
  }
  .date-box {
    height: 50px;
    line-height: 50px;
  }
}
.filter-popup{
  position: fixed;
  top: 88px;
  width: 100vw;

  z-index: 10;
  .filter-bg{
    position: absolute;
    background: rgba(0,0,0,0.4);
    height: calc(100vh - 88px);
    width: 100%;
  }
  .filter-content{
    position: relative;
    z-index: 1;
    background: $colorF;
    .filter-item{
      color: $color9;
      font-size: 28px;
      line-height: 1.5;
      border-radius: 28px;
      border: 1px solid currentColor;
      text-align: center;
      padding: 0 30px;
    }
    .activeDate{
      @include color-primary;
    }
    input{
      font-size: 28px;
      line-height: 1;
      padding: 7px 20px;
      border: 1px solid $color9;
      border-radius: 28px;
      width:300px;

    }
  }
}
</style>
